package com.icebergteam.resumemaster;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

//import com.icebergteam.resumemaster.PdfManager;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;

import com.itextpdf.text.Paragraph;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.html.simpleparser.StyleSheet;
import com.itextpdf.text.pdf.PdfWriter;

//import com.icebergteam.resumemaster.PdfManager;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;


import com.icebergteam.resumemaster.*;

public class MainActivity extends Activity {
	private static final int SHOW_MESSAGEACTIVITY = 1;
	//private static String FILE = PdfManager.FILE;
	
	private InputStream OpenHttpConnection(String strURL) throws IOException {
		URLConnection conn = null;
		InputStream inputStream = null;
		URL url = new URL(strURL);
		conn = url.openConnection();
		HttpURLConnection httpConn = (HttpURLConnection) conn;
		httpConn.setRequestMethod("GET");
		httpConn.connect();
		if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			inputStream = httpConn.getInputStream();
		}
		return inputStream;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

	//	generatePdf();
	}

	/*private void generatePdf() {
		Document document = new Document();
		File root = new File(Environment.getExternalStorageDirectory(), "Notes");
		if (!root.exists()) {
			root.mkdirs();
		}
		File gpxfile = new File(root, "generando.pdf");
		PdfWriter writer = null;
		try {
			writer = PdfWriter.getInstance(document, new FileOutputStream(
					gpxfile));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		document.open();
		try {
			/*
			 * ByteArrayOutputStream stream = new ByteArrayOutputStream();
			 * Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
			 * R.drawable.ic_launcher);
			 * bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); Image
			 * image = Image.getInstance(stream.toByteArray());
			 * image.setRotationDegrees(45f);
			 * 
			 * //String imageUrl =
			 * "http://javac.in/wp-content/themes/Whitey/images/javac.jpg";
			 * //Image image2 = Image.getInstance(imageUrl);
			 * 
			 * document.add(image); // document.add(image2);
			 * 
			 * /* add image from bytearray
			 */
			/*
			 * stream = new ByteArrayOutputStream(); bitmap =
			 * BitmapFactory.decodeStream
			 * (OpenHttpConnection("http://www.rgagnon.com/images/javahowto.jpg"
			 * )); bitmap.compress(Bitmap.CompressFormat.JPEG , 100 , stream);
			 * document.add(Image.getInstance(stream.toByteArray()));
			 */

	/*		PdfManager pdf = new PdfManager(this.getResources());
			pdf.addMetaData(document);
			pdf.addTitlePage(document);
			pdf.addContent(document);

			HTMLWorker htmlWorker = new HTMLWorker(document);

			String str = "<html><head><style type='text/css' media='screen'>body{color:red;}</style></head><body bgcolor='red' style='background-color: #FF0000'>"
					+ "<a href='http://www.rgagnon.com/howto.html'><b>Real's HowTo</b></a>"
					+ "<h1>Show your support</h1>"
					+ "<p bgcolor='red'>It DOES cost a lot to produce this site - in ISP storage and transfer fees, "
					+ "in personal hardware and software costs to set up test environments, and above all,"
					+ "the huge amounts of time it takes for one person to design and write the actual content."
					+ "<p style='background-color: #FF0000'>If you feel that effort has been useful to you, perhaps you will consider giving something back?"
					+ "<p>Donate using PayPal� to real@rgagnon.com."
					+ "<p>Contributions via PayPal ��������� are accepted in any amount "
					+ "<P><br><table border='1'><tr><td>Java HowTo<tr>"
					+ "<td bgcolor='red'>Javascript HowTo ������ �����<tr><td>Powerbuilder HowTo</table>"
					+ "</body></html>";
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("font_factory", new ResumeFontFactory());

			StyleSheet style = new StyleSheet();
			style.loadTagStyle("body", "color", "red");
			style.loadStyle("h1", "font-size", "10px");

			htmlWorker.setStyleSheet(style);

			List<Element> objects = htmlWorker.parseToList(
					new StringReader(str)/*
										 * new FileReader(Uri.parse(
										 * "android.resource://com.icebergteam.resumemaster/res/raw/rmagit.html"
										 * ).getEncodedPath())
										 *//*, null, map);

			/*
			 * Map<String, String> pc2 = new HashMap<String, String>();
			 * pc2.put("line-height", "115%"); pc2.put("margin-bottom",
			 * "6.0pt"); pc2.put("text-align", "center");
			 * 
			 * Map<String, String> spanc1 = new HashMap<String, String>();
			 * spanc1.put("line-height", "115%"); spanc1.put("font-family",
			 * "\"Arial\",serif"); spanc1.put("color", "black");
			 * spanc1.put("letter-spacing", "10pt");
			 * 
			 * StyleSheet styles = new StyleSheet(); styles.loadTagStyle("p",
			 * pc2); styles.loadTagStyle("span", spanc1);
			 */

		/*	for (Element element : objects) {
				document.add(element);
			}

			// XMLWorkerHelper.getInstance().parseXHtml(writer, document,
			// MainActivity.class.getResourceAsStream(Uri.parse("http://google.com").getEncodedPath()));

			// ITextRenderer renderer;

	/*	} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		document.close();
	}*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void SwitchActivity(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.editResume:
			intent = new Intent(MainActivity.this, Editor.class);
			startActivity(intent);
			break;
		case R.id.chooseTemplate:
			break;
		case R.id.viewResume:
			intent = new Intent(MainActivity.this, WebKitActivity.class);
			intent.putExtra("url", WebKitActivity.DEFAULHTURL	+ "ResumeTemplate/index.html");
			
			//intent.putExtra("url", "file:///mnt/sdcard/test2/test.html?xml=android_assetestl");
			startActivityForResult(intent, SHOW_MESSAGEACTIVITY);
			break;
		case R.id.sendResume:
			break;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	  //Handle the back button
	  if (keyCode == KeyEvent.KEYCODE_BACK) {
	    //Ask the user if they want to quit
	    new AlertDialog.Builder(this)
	      .setIcon(android.R.drawable.ic_dialog_alert)
	      .setTitle("Exit")
	      .setMessage("Are you sure you want to leave?")
	      .setNegativeButton(android.R.string.cancel, null)
	      .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
	      
	        public void onClick(DialogInterface dialog, int which){
	          // Exit the activity
	          MainActivity.this.finish();
	        }
	      })
	      .show();

	    // Say that we've consumed the event
	    return true;
	  }

	  return super.onKeyDown(keyCode, event);
	} 

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SHOW_MESSAGEACTIVITY) {
			String name = data.getStringExtra("load");
			Toast.makeText(
					this,
					String.format("Activity responce: %s, code:%d", name,
							resultCode), Toast.LENGTH_SHORT).show();
		}
	}
	public void onDestroy() {
	    super.onDestroy();
	   
	    /*
	     * Notify the system to finalize and collect all objects of the
	     * application on exit so that the process running the application can
	     * be killed by the system without causing issues. NOTE: If this is set
	     * to true then the process will not be killed until all of its threads
	     * have closed.
	     */
	   System.runFinalizersOnExit(true);

	    /*
	     * Force the system to close the application down completely instead of
	     * retaining it in the background. The process that runs the application
	     * will be killed. The application will be completely created as a new
	     * application in a new process if the user starts the application
	     * again.
	     */
	    System.exit(0);
	}
}